﻿using Mate.Caching;
using Mate.Db.Model.Info;
using Mate.Db.Model.Merchant;
using Mate.Db.SqlSugar;
using Mate.Dto.Merchant;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Mate.Db.Model.Comment;

namespace Mate.Merchant.Service
{
    public class MerchantService : DataService<mp_merchant>, IMerchantService
    {
        private readonly ICacheManager _cache;
        public MerchantService(DataClient dataClient, ICacheManager cache) : base(dataClient)
        {
            this._cache = cache;
        }

        #region 获取商户信息
        /// <summary>
        /// 获取商户列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="Key"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public IList<MerchantModel> GetMerchantList(int pageIndex, int pageSize, string Key, ref int recordCount)
        {
            return dataClient.Queryable<mp_merchant, mp_merchant_category, mp_district>((m, mc, d) => new object[]{
                JoinType.Left,m.merchantcategory==mc.id,
                JoinType.Left,m.merchantdistrict==d.id
                })
                .Where((m, mc, d) => m.is_delete ==1)
                .WhereIF(!string.IsNullOrWhiteSpace(Key), (m, mc, d) => m.merchantname.Contains(Key))
                .OrderBy((m, mc, d) => m.id, OrderByType.Desc)
                .Select<MerchantModel>("m.*,mc.merchantcategoryname,d.districtname")
                .ToPageList(pageIndex, pageSize, ref recordCount);
        }
        #endregion

        #region 筛选商户
        /// <summary>
        /// 筛选商户
        /// </summary>
        /// <param name="pageIndex">当前页</param>
        /// <param name="pageSize">每页条数</param>
        /// <param name="merchantcategory">商户类型id</param>
        /// <param name="is_hot">是否热门1是 0否</param>
        /// <param name="merchantname">商户名称</param>
        /// <param name="sortType">1评分，2点评数</param>
        /// <param name="isNew">是否按新店排序  1查询最近一个月添加的商家</param>
        /// <param name="isBrand">是否查询品牌商户  1是</param>
        /// <param name="recordCount">总条数</param>
        /// <returns></returns>
        public IList<MerchantSearchDto> MerchantSearch(int pageIndex, int pageSize, IEnumerable<int> merchantcategory,int? is_hot, string merchantname, int sortType,
            int isNew, int isBrand, ref int recordCount)
        {
            string sortStr = " s.score desc";
            switch (sortType)
            {
                case 1:
                    sortStr = " s.score desc";
                    break;
                case 2:
                    sortStr = " commentcount desc";
                    break;
                case 3:
                    sortStr = " m.createtime desc";
                    break;
            }

            DateTime startDate = DateTime.Now.AddMonths(-1).Date;
            DateTime endDate = DateTime.Now;

            return dataClient.Queryable<mp_merchant, mp_merchant_category, mp_score>((m, mc, s) => new object[]
              {
                JoinType.Left,m.merchantcategory==mc.id,
                JoinType.Left,m.id==s.relateid&&s.score_type==1
              })
            .WhereIF(merchantcategory.Count() > 0, (m, mc, s) => merchantcategory.Contains(m.merchantcategory))
            .WhereIF(is_hot > -1, (m, mc, s) => m.is_hot == is_hot)
            .WhereIF(!string.IsNullOrWhiteSpace(merchantname), (m, mc, s) => m.merchantname.Contains(merchantname))
            .WhereIF(isNew == 1, (m, mc, s) => m.createtime >= startDate && m.createtime <= endDate)
            .WhereIF(isBrand == 1, (m, mc, s) => m.is_brand == 1)
            .Where((m, mc, s) => m.is_delete == 1 && m.is_audit == 1)
            .OrderBy(sortStr)
            //.OrderBy((m, mc, s) => s.score, OrderByType.Desc)
            .Select<MerchantSearchDto>(@"m.id,
            m.merchantname,
            m.merchantlogo,
            m.merchantaddress,
            m.merchantcategory,
            mc.merchantcategoryname,
            m.is_hot,
            m.createtime,
            m.is_brand,
            m.brand_name,
            (select score from mp_score where score_type=1 and relateid=m.id LIMIT 1) score,
            m.percost,
            (select count(1) from mp_comment where comment_type=10 and relateid=m.id) commentcount")
             .ToPageList(pageIndex, pageSize, ref recordCount);
           
        }
        #endregion

        #region 获取商户详情
        /// <summary>
        /// 获取商户详情
        /// </summary>
        /// <param name="merchantId">商户id</param>
        /// <returns></returns>
        public MerchantDetailDto MerchantDetail(int merchantId)
        {
            var model = dataClient.Queryable<mp_merchant, mp_merchant_category, mp_score, mp_district>((m, mc, s, d) => new object[]{
                JoinType.Left,m.merchantcategory==mc.id,
                JoinType.Left,m.id==s.relateid&&s.score_type==1,
                JoinType.Left,m.merchantdistrict==d.id
                })
               .Where((m, mc, s, d) => m.is_delete == 1 && m.id == merchantId)
               .Select((m, mc, s, d) => new MerchantDetailDto()
               {
                   id = m.id,
                   merchantname = m.merchantname,
                   merchantlogo = m.merchantlogo,
                   score = s.score,
                   percost = m.percost,
                   tastescore = s.tastescore,
                   enviromentscore = s.enviromentscore,
                   servicescore = s.servicescore,
                   merchantcategory = m.merchantcategory,
                   merchantcategoryname = mc.merchantcategoryname,
                   merchanttag = m.merchanttag,
                   merchantdistrict = m.merchantdistrict,
                   districtname = d.districtname
               })
               .First();
            if (model == null || model.id == 0)
            {
                return null;
            }
            //点评数
            model.commentcount = dataClient.Queryable<mp_comment>()
                .Where(x => x.comment_type == 10 && x.relateid == model.id && x.is_delete == 1 && x.is_audit == 1).Count();

            var opentimeList = dataClient.Queryable<mp_merchant_opentime>()
                .Where(x => x.merchantid == model.id && x.is_delete == 1 && x.is_open == 1).ToList();
            if (opentimeList != null)
            {
                model.opentime = string.Join(',', opentimeList.Select(x => x.merchantopenbegin + "-" + x.merchantopenend));
                model.openstatus = "暂停营业";
                foreach (var opentime in opentimeList)
                {
                    var sTime = Convert.ToDateTime(DateTime.Now.Date.ToString("yyyy-MM-dd") + " " + opentime.merchantopenbegin);
                    var eTime = Convert.ToDateTime(DateTime.Now.Date.ToString("yyyy-MM-dd") + " " + opentime.merchantopenend);
                    if (DateTime.Now >= sTime && DateTime.Now < eTime)
                    {
                        model.openstatus = "营业中";
                        break;
                    }
                }
            }
            return model;
        }
        #endregion
    }
}
